﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using CommonModule;
using System.Data;
using Microsoft.Practices.Unity;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.Services;
using Web.SystemConfig.SysCache;
using Web.SystemConfig.WorkFlow;
using DreamBuilder.Core.Container;
using ePlanet.SingleWell.Business;
using Web.SystemConfig.Models;
using Web.SystemConfig.Services;
using Web.SystemConfig.Business;
using Web.SystemLogin.Models;

namespace Web.Views.SingleWellManage
{
    public partial class SingleWellEdit : PageBase
    {
        #region 页面变量
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }
        [Dependency]
        public ISingleWellService m_ISingleWellService
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_Role m_IAuth_Role
        {
            get;
            set;
        }

        [Dependency]
        public IWellCatalogService m_IWellCatalogService
        {
            get;
            set;
        }

        [Dependency]
        public IAttachmentService m_IAttachmentService
        {
            get;
            set;
        }

        private string m_WellDataID
        {
            get
            {
                if (Request.QueryString["RecordID"] != null)
                {
                    return Request.QueryString["RecordID"];
                }
                else
                {
                    this.amSingleWell.ObjectID = Guid.NewGuid().ToString();
                    return this.amSingleWell.ObjectID;
                }
            }
        }

        private string m_WellType
        {
            get
            {
                if (Request.QueryString["wellType"] != null)
                {
                    if (Request.QueryString["wellType"] != "1")
                    {
                        ViewState["wellType"] = Request.QueryString["wellType"];
                    }
                    else
                    {
                        ViewState["wellType"] = m_IWellCatalogService.GetBaseCatalog().WELLCATALOG[0]["WellCataLogID"].ToString();
                    }
                }
                else
                {
                    ViewState["wellType"] = m_IWellCatalogService.GetBaseCatalog().WELLCATALOG[0]["WellCataLogID"].ToString();
                }

                return ViewState["wellType"].ToString();
            }
        }

        private Web.SystemLogin.Models.User currentUser
        {
            get
            {
                return (Web.SystemLogin.Models.User)Session["CurrentUser"];
            }
        }

        private bool canView
        {
            get
            {
                if (!this.IsFromDataManage)
                {
                    if (ViewState["canView'"] != null)
                    {
                        return bool.Parse(ViewState["canView'"].ToString());
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            set
            {
                ViewState["canView'"] = value;
            }
        }
        private bool canEdit
        {
            get
            {
                if (!this.IsFromDataManage)
                {
                    if (ViewState["canEdit'"] != null)
                    {
                        return bool.Parse(ViewState["canEdit'"].ToString());
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            set
            {
                ViewState["canEdit'"] = value;
            }
        }
        private bool canOperate
        {
            get
            {
                if (!this.IsFromDataManage)
                {
                    if (ViewState["canOperate'"] != null)
                    {
                        return bool.Parse(ViewState["canOperate'"].ToString());
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            set
            {
                ViewState["canOperate'"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["RecordID"]))
                    {
                        CurrentPageState = PageState.State_Edit;
                    }

                    SingleWellModel model = this.m_ISingleWellService.GetSingleWellModel(m_WellDataID);
                    //this.InitDBO();

                    /********初始化类型信息*********/

                    BindDdlType();

                    if (!this.IsFromDataManage)
                    {
                        this.GetPrivilege(model);
                    }
                    this.InitPage(model);
                    this.InitAttachmentInfos();
                    if (!this.IsFromDataManage)
                    {
                        this.SetControlEnable();
                    }
                    else
                    {
                        this.btnAddSingelWell.Visible = false;
                        this.btnDelete1.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    Alert("页面异常：" + ex.Message);
                }
            }
        }

        #region 初始化页面
        #region 获取数据浏览权限、数据编辑权限、数据操作权限
        /// <summary>
        /// 获取数据权限
        /// </summary>
        private void GetPrivilege(SingleWellModel model)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["RecordID"]))
            {
                WorkFlow oWorkFlow = new WorkFlow();
                ///签收数据
                WorkFlowModel oWorkFlowModel = new WorkFlowModel();
                oWorkFlowModel.TableID = (int)ArchiveTableEnum.SingleWell;
                oWorkFlowModel.RecordID = new Guid(model.SINGLEWELL[0].DATAID);
                oWorkFlowModel.FromStatusID = (int)model.SINGLEWELL[0].STATUSID;
                oWorkFlowModel.FromUserID = new Guid(currentUser.User_ID);
                oWorkFlow.SignData(oWorkFlowModel);

                bool edit = false;
                bool view = false;
                bool operate = false;

                string strMsg = oWorkFlow.GetPrivilege(ArchiveTableEnum.SingleWell, this.currentUser.User_ID, this.m_WellDataID, ref edit, ref view, ref operate);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    canView = false;
                    canEdit = false;
                    canOperate = false;
                }
                else
                {
                    canView = view;
                    canEdit = edit;
                    canOperate = operate;
                }
            }
            else
            {
                this.canView = true;
                this.canOperate = true;
                this.canEdit = true;
            }
        }

        /// <summary>
        /// 设置可编辑权限
        /// </summary>
        private void SetControlEnable()
        {
            if (!this.canEdit)
            {
                this.txtA0.Enabled = false;
                this.txtA3.Enabled = false;
                this.txtA4.Enabled = false;
                //this.txtArchiveCode.Enabled = false;
                this.txtBEGINDATE.Enabled = false;
                this.txtBeginWorkDate.Enabled = false;
                this.txtDatafileName.Enabled = false;
                this.txtFINISHDATE.Enabled = false;
                this.txtFinishWorkDate.Enabled = false;
                //this.txtQuanzongCode.Enabled = false;
                this.txtWellCode.Enabled = false;
                this.txtWellDepth.Enabled = false;
                this.txtWorkMode.Enabled = false;
                this.txtWellType.Enabled = false;
                this.btnAddDetail.Visible = false;
                this.btnSaveDetail.Visible = false;
                this.btnAddSingelWell.Visible = false;
            }
            else
            {
                this.btnAddDetail.Visible = true;
                this.btnSaveDetail.Visible = false;
                this.btnAddSingelWell.Visible = false;
            }
        }

        /// <summary>
        /// 设置数据浏览操作编辑权限
        /// </summary>
        /// <param name="model"></param>
        private void InitPage(SingleWellModel model)
        {
            ///有值表示修改
            if (!string.IsNullOrEmpty(Request.QueryString["RecordID"]))
            {
                //判断是否拥有浏览权限
                if (canView)
                {
                    //初始化控件值
                    if (model != null && model.SINGLEWELL.Rows.Count > 0)
                    {
                        if (!canOperate)
                        {
                            //设置操作按钮的显隐
                            this.btnSaveAndSendSingelWell.Visible = false;
                            this.btnDelete1.Visible = false;
                            this.btnAddSingelWell.Visible = false;
                        }

                        ///绑定单井数据
                        SingleWellModel.SINGLEWELLRow singleRow = null;
                        if (model.SINGLEWELL != null && model.SINGLEWELL.Count > 0)
                        {
                            singleRow = model.SINGLEWELL[0];
                            this.BindSingleModel(singleRow);
                        }

                        ///绑定详细
                        if (model.WELLDATADETAIL != null)
                        {
                            this.BindDetailModel(model.WELLDATADETAIL);
                        }
                    }
                    else
                    {
                        throw new Exception("获取的数据集为空");
                    }
                }
                else
                {
                    Alert("您无权限查看此数据");
                }
            }
            else
            {
                //表示新建元数据
                WellCatalog oWellCatalog = m_IWellCatalogService.GetWellCatalogByID(this.m_WellType);
                this.txtWellCode.Text = oWellCatalog.WELLCATALOG[0]["CATALOGDESCRIPT"].ToString();
            }
        }
        #endregion

        /// <summary>
        /// 设置详细操作按钮显隐
        /// </summary>
        /// <param name="b"></param>
        private void SetButtonVisible(bool b)
        {
            this.detailDiv.Visible = b;
            this.btnAddDetail.Visible = b;
        }

        /// <summary>
        /// 初始化类型信息
        /// </summary>
        private void BindDdlType()
        {
            //类别信息
            DataSet dtCategory = CodeTableService.GetCodeTableDataByType("WellCategory");
            if (dtCategory != null && dtCategory.Tables.Count > 0)
            {
                this.ddlType.DataSource = dtCategory;
                this.ddlType.DataTextField = "Code_Desc";
                this.ddlType.DataValueField = "CodeTableID";
                this.ddlType.DataBind();
                this.ddlType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            //初始化详细类别
            if (this.ddlType.SelectedIndex > 0)
            {
                DataSet dtDetail = CodeTableService.GetCodeTableDataByType(ddlType.SelectedValue);
                if (dtDetail != null && dtDetail.Tables.Count > 0)
                {
                    this.ddlDetailType.DataSource = dtDetail;
                    this.ddlDetailType.DataTextField = "Code_Desc";
                    this.ddlDetailType.DataValueField = "CodeTableID";
                    this.ddlDetailType.DataBind();
                    this.ddlDetailType.Items.Insert(0, new ListItem("--请选择--", "-1"));
                }
            }
            else
            {
                this.ddlDetailType.Items.Insert(0, new ListItem("--无数据--", "-1"));
            }
        }
        #endregion

        #region 附件操作
        private void InitAttachmentInfos()
        {
            if (this.canEdit)
            {
                this.divAttach.Visible = true;
                this.divGv.Visible = false;
                this.SetAttachmentInfoParams();
                this.AddAttachmentInfos();
            }
            else
            {
                this.divGv.Visible = true;
                this.divAttach.Visible = false;
            }
            this.BindAttachToGV();
        }

        /// <summary>
        /// 绑定附件数据到GV
        /// </summary>
        private void BindAttachToGV()
        {
            DataTable oDataTable = null;
            this.m_IAttachmentService.Initialize("SingleWell");
            List<AttachmentModel> modelList = this.m_IAttachmentService.GetAttachmentModelByObjectID(this.m_WellDataID);
            if (modelList != null && modelList.Count > 0)
            {
                oDataTable = new DataTable();
                oDataTable.Columns.Add("attachmentid");
                oDataTable.Columns.Add("attachmentname");
                oDataTable.Columns.Add("uploadtime");
                oDataTable.Columns.Add("attachmentsize");

                foreach (AttachmentModel model in modelList)
                {
                    DataRow dr = oDataTable.NewRow();
                    dr["attachmentid"] = model.AttachmentID;
                    dr["attachmentname"] = model.AttachmentName;
                    dr["uploadtime"] = model.UpdateTime;
                    dr["attachmentsize"] = (model.AttachmentSize / (1000 * 1000) > 0) ? (Math.Round((float)model.AttachmentSize / (1000 * 1000), 3) + "MB") : Math.Round((float)model.AttachmentSize / (1000)) + "KB";

                    oDataTable.Rows.Add(dr);
                }
            }
            if (oDataTable != null && oDataTable.Rows.Count > 0)
            {
                this.gv_Attach.DataSource = oDataTable;
                this.gv_Attach.DataBind();
            }
        }

        /// <summary>
        /// 附件实体增加更多信息
        /// </summary>
        private void AddAttachmentInfos()
        {
            Hashtable addInfos = new Hashtable();
            addInfos.Add("FunctionID", "0"); //功能ID(1：发文文档 2：发文附件 3：收文文档 4：收文附件 5：即时消息附件 6：新闻附件)
            addInfos.Add("FileTypeID", ""); //附件文件夹类型
            addInfos.Add("FileURL", ""); //附件存储路径
            addInfos.Add("IsXml", "0"); //是否XML代码化
            addInfos.Add("CreateUserID", this.CurrentUser.User_ID); //用户ID 目前可以写个固定的值作为测试
            addInfos.Add("Remark", "即时消息附件"); //备注
            if (Session["AddInfos"] == null)
            {
                Session.Add("AddInfos", addInfos);
            }
            else
            {
                Session.Remove("AddInfos");
                Session.Add("AddInfos", addInfos);
            }
        }

        private void SetAttachmentInfoParams()
        {
            this.amSingleWell.ObjectTableName = "singlewell";
            this.amSingleWell.ObjectID = this.m_WellDataID;
        }
        #endregion

        #region 按钮事件
        protected void btnAddDetail_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.detailDiv.Visible)
                {
                    SetButtonVisible(true);
                    this.btnAddDetail.Text = "保存详细";
                }
                else
                {
                    this.BindDetail();
                }
            }
            catch (Exception ex)
            {
                Alert("页面异常：" + ex.Message);
            }
        }

        protected void btnSaveDetail_Click(object sender, EventArgs e)
        {
            try
            {
                this.SetButtonVisible(!this.detailDiv.Visible);
            }
            catch (Exception ex)
            {
                Alert("页面异常：" + ex.Message);
            }
        }

        protected void btnAddSingelWell_Click(object sender, EventArgs e)
        {
            try
            {
                Guid userID = Guid.Empty;
                User currentUser = (User)Session["CurrentUser"];
                if (currentUser != null)
                {
                    userID = new Guid(currentUser.User_ID);
                }
                Guid recordID = this.AddNewData();
                FlowStart(recordID, userID, -1);
                WriteUserLog(string.Format("用户{0}录入了{1}的单井数据", currentUser.Real_Name, recordID), OracleLogType.SingleWell);
                MyAlert("临时保存成功", "SingleWellEntryView.aspx?jobtype=1");
            }
            catch (Exception ex)
            {
                Alert("页面异常：" + ex.Message);
            }
        }

        protected void btnSaveAndGoon_Click(object sender, EventArgs e)
        {
            try
            {
                Guid userID = Guid.Empty;
                User currentUser = (User)Session["CurrentUser"];
                if (currentUser != null)
                {
                    userID = new Guid(currentUser.User_ID);
                }
                Guid recordID = this.AddNewData();
                FlowStart(recordID, userID, -1);
                Alert("保存成功");
            }
            catch (Exception ex)
            {
                Alert("页面异常：" + ex.Message);
            }
        }

        protected void btnSaveAndSendSingelWell_Click(object sender, EventArgs e)
        {
            try
            {
                Guid userID = Guid.Empty;
                User currentUser = (User)Session["CurrentUser"];
                if (currentUser != null)
                {
                    userID = new Guid(currentUser.User_ID);
                }
                Guid recordID = Guid.Empty;
                recordID = this.AddNewData();
                if (!this.IsFromDataManage)
                {
                    FlowProcess(recordID, userID, -1);
                    MyAlert("保存并上报数据成功", "SingleWellEntryView.aspx?jobtype=1");
                }
                else
                {
                    Alert("保存数据成功");
                }
            }
            catch (Exception ex)
            {
                Alert("页面异常：" + ex.Message);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (DeleteData())
                {
                    MyAlert("删除数据成功", "singlewellEntryView.aspx?jobtype=1");
                }
            }
            catch (Exception ex)
            {
                Alert("删除数据出错：" + ex.Message);
            }
        }

        protected void gv_SingleWellDetail_OnDataBound(object sender, EventArgs e)
        {
            DreamBuilder.UI.UserControls.EPGridView oEPGridView = sender as DreamBuilder.UI.UserControls.EPGridView;
            if (!this.canEdit)
            {
                oEPGridView.Columns[0].Visible = false;
            }
            if (string.IsNullOrEmpty(Request.QueryString["DataID"]))
            {
                oEPGridView.Columns[1].Visible = false;
                oEPGridView.Columns[2].Visible = true;
            }
            else
            {
                oEPGridView.Columns[1].Visible = true;
                oEPGridView.Columns[2].Visible = false;
            }
        }

        protected void gv_Attach_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            //if (e.CommandName.ToLower() == "down".ToLower())
            //{
            //    DreamBuilder.UI.UserControls.EPGridView oEPGridView = sender as DreamBuilder.UI.UserControls.EPGridView;
            //    string attachmentID = ((DataTable)oEPGridView.DataSource).Rows[int.Parse(e.CommandArgument.ToString())][0].ToString();
            //    string url = Request.Url.ToString().ToLower().Substring(0, Request.Url.ToString().ToLower().IndexOf("SingleWellEntry".ToLower())) + "SingleWellAttachDownload.aspx?AttachmentID" + attachmentID;
            //    Response.Write("<Script language='JavaScript'>window.open('" + url + "')</Script>");
            //}
        }
        #endregion

        #region 私有方法

        /// <summary>
        /// 添加新数据
        /// </summary>
        private Guid AddNewData()
        {
            if (this.CheckNull())
            {
                SingleWellModel model = new SingleWellModel();
                Guid wellDataID = new Guid(this.m_WellDataID);
                SingleWellModel.SINGLEWELLRow singleRow = this.CollectSingleWellRow(model, wellDataID);
                this.CollectWellDataDetailRow(model, wellDataID);
                model.SINGLEWELL.AddSINGLEWELLRow(singleRow);
                if (this.CurrentPageState == PageState.State_Edit)
                {
                    singleRow.AcceptChanges();
                    singleRow.SetModified();
                }
                m_ISingleWellService.AddSingleWell(model);

                if (this.SaveAttachment())
                {
                    return wellDataID;
                }
                else
                {
                    throw new Exception("保存附件失败");
                }
            }
            else
            {
                return Guid.NewGuid();
            }
        }

        private bool DeleteData()
        {
            SingleWellModel model = new SingleWellModel();
            Guid wellDataID = new Guid(this.m_WellDataID);
            SingleWellModel.SINGLEWELLRow singleRow = this.CollectSingleWellRow(model, wellDataID);
            this.CollectWellDataDetailRow(model, wellDataID);
            model.SINGLEWELL.AddSINGLEWELLRow(singleRow);
            return m_ISingleWellService.DeleteSingleWell(model);
        }

        private bool SaveAttachment()
        {
            DataTable dt_Attach = this.amSingleWell.GetSaveDataTable(this.amSingleWell.ObjectID, this.amSingleWell.ObjectTableName);
            IAttachmentService oIAttachmentService = UContainer.Resolve<IAttachmentService>();
            oIAttachmentService.Initialize(this.amSingleWell.AttachmentDBHelperString);
            return oIAttachmentService.SaveAttach(dt_Attach, this.amSingleWell.ObjectTableName, this.amSingleWell.ObjectID);
        }

        /// <summary>
        /// 实例化SingleWellRow对象
        /// </summary>
        /// <param name="model"></param>
        /// <param name="wellDataID"></param>
        /// <returns></returns>
        private SingleWellModel.SINGLEWELLRow CollectSingleWellRow(SingleWellModel model, Guid wellDataID)
        {
            SingleWellModel.SINGLEWELLRow rtnSingleRow = model.SINGLEWELL.NewSINGLEWELLRow();
            //实例化SingleWellData
            if (!string.IsNullOrEmpty(this.txtA0.Text))
            {
                rtnSingleRow.A0 = int.Parse(this.txtA0.Text.Trim());
            }
            if ((!string.IsNullOrEmpty(this.txtA3.Text)))
            {
                rtnSingleRow.A3 = int.Parse(this.txtA3.Text);
            }
            if ((!string.IsNullOrEmpty(this.txtA4.Text)))
            {
                rtnSingleRow.A4 = int.Parse(this.txtA4.Text);
            }
            if (!string.IsNullOrEmpty(this.txtBEGINDATE.Text.Trim()))
            {
                rtnSingleRow.BEGINDATE = DateTime.Parse(this.txtBEGINDATE.Text.Trim());//开工日期
            }
            if (!string.IsNullOrEmpty(this.txtFINISHDATE.Text.Trim()))
            {
                rtnSingleRow.FINISHDATE = DateTime.Parse(this.txtFINISHDATE.Text.Trim());//完工日期
            }
            if (!string.IsNullOrEmpty(this.txtBeginWorkDate.Text.Trim()))
            {
                rtnSingleRow.BEGINWORKDATE = DateTime.Parse(this.txtBeginWorkDate.Text.Trim());//开钻日期
            }
            if (!string.IsNullOrEmpty(this.txtFinishWorkDate.Text.Trim()))
            {
                rtnSingleRow.FINISHWORKDATE = DateTime.Parse(this.txtFinishWorkDate.Text.Trim());//完钻日期
            }
            /*******************************
            * add by guoyin 2014-03-25
            * 增加单井类型和子类型(数据加载)
            *******************************/
            if (this.ddlType.SelectedIndex > 0)
            {
                rtnSingleRow.CATEGORY = this.ddlType.SelectedValue;
            }

            if (this.ddlDetailType.SelectedIndex > 0)
            {
                rtnSingleRow.CATEGORYDETAIL = this.ddlDetailType.SelectedValue;
            }
            /* end */
            rtnSingleRow.DATAFILENAME = this.txtDatafileName.Text.Trim();//文件名
            rtnSingleRow.INSERTTIME = DateTime.Now;//新建时间
            rtnSingleRow.STATUSID = 0;
            rtnSingleRow.CREATEUSERID = currentUser.User_ID;
            rtnSingleRow.WELLCODE = this.txtWellCode.Text.Trim();
            rtnSingleRow.DATAID = wellDataID.ToString();
            if (!string.IsNullOrEmpty(this.txtWellDepth.Text.Trim()))
            {
                rtnSingleRow.WELLDEPTH = decimal.Parse(this.txtWellDepth.Text.Trim());
            }
            else
            {
                rtnSingleRow.WELLDEPTH = 0;
            }

            if (CurrentPageState == PageState.State_Edit)
            {
                SingleWellModel.SINGLEWELLDataTable table = this.m_ISingleWellService.GetSingleWellModel(wellDataID.ToString()).SINGLEWELL;
                if (table != null && table.Rows.Count > 0)
                {
                    SingleWellModel.SINGLEWELLRow row = table.Rows[0] as SingleWellModel.SINGLEWELLRow;
                    if (row != null)
                    {
                        rtnSingleRow.WELLCATALOGID = row.WELLCATALOGID;
                        rtnSingleRow.STATUSID = row.STATUSID;
                    }
                }
            }
            else
            {
                rtnSingleRow.WELLCATALOGID = this.m_WellType;
            }


            rtnSingleRow.WELLTYPE = this.txtWellType.Text.Trim();
            rtnSingleRow.WORKMODE = this.txtWorkMode.Text.Trim();
            return rtnSingleRow;
        }

        /// <summary>
        /// 实例化WellDataDetailRow对象
        /// </summary>
        /// <param name="model"></param>
        /// <param name="wellDataID"></param>
        /// <returns></returns>
        private void CollectWellDataDetailRow(SingleWellModel model, Guid wellDataID)
        {
            List<string> details = new List<string>();
            if (CurrentPageState == PageState.State_Edit)
            {
                SingleWellModel oldModel = this.m_ISingleWellService.GetSingleWellModel(wellDataID.ToString());

                for (int i = 0; i < oldModel.WELLDATADETAIL.Count; i++)
                {
                    details.Add(oldModel.WELLDATADETAIL[i].DETAILID);
                }
            }

            SingleWellModel.WELLDATADETAILRow detailRow = null;
            //实例化DetailData
            DataTable detailDt = this.gv_SingleWellDetail.DataSource as DataTable;
            if (detailDt != null && detailDt.Rows.Count > 0)
            {
                foreach (DataRow dr in detailDt.Rows)
                {
                    detailRow = model.WELLDATADETAIL.NewWELLDATADETAILRow();
                    detailRow.DETAILNAME = dr["detailname"].ToString();
                    if (dr["A4"] != DBNull.Value && !string.IsNullOrEmpty(dr["A4"].ToString()))
                    {
                        detailRow.A4 = int.Parse(dr["A4"].ToString());
                    }
                    if (dr["A3"] != DBNull.Value && !string.IsNullOrEmpty(dr["A3"].ToString()))
                    {
                        detailRow.A3 = int.Parse(dr["A3"].ToString());
                    }
                    if (dr["A0"] != DBNull.Value && !string.IsNullOrEmpty(dr["A0"].ToString()))
                    {
                        detailRow.A0 = int.Parse(dr["A0"].ToString());
                    }
                    if (dr["PageNum"] != DBNull.Value && !string.IsNullOrEmpty(dr["PageNum"].ToString()))
                    {
                        detailRow.PAGENUM = int.Parse(dr["PageNum"].ToString());
                    }
                    if (dr["DETAILID"] != DBNull.Value && !string.IsNullOrEmpty(dr["DETAILID"].ToString()))
                    {
                        detailRow.DETAILID = dr["DETAILID"].ToString();
                    }
                    ///
                    detailRow.WELLDATAID = wellDataID.ToString();
                    model.WELLDATADETAIL.AddWELLDATADETAILRow(detailRow);

                    if (CurrentPageState == PageState.State_Edit)
                    {
                        if (details.Contains(detailRow.DETAILID))
                        {
                            detailRow.AcceptChanges();
                            detailRow.SetModified();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 检测必填项
        /// </summary>
        /// <returns></returns>
        private bool CheckNull()
        {
            if (string.IsNullOrEmpty(this.txtDatafileName.Text))
            {
                throw new Exception("文件名不能为空");
            }

            //检测A0数据有效性
            if (!string.IsNullOrEmpty(this.txtA0.Text.Trim()))
            {
                try
                {
                    decimal.Parse(this.txtA0.Text.Trim());
                }
                catch
                {
                    throw new Exception("所填写的A0不是数字");
                }
            }

            //检测A3数据有效性
            if (!string.IsNullOrEmpty(this.txtA3.Text.Trim()))
            {
                try
                {
                    decimal.Parse(this.txtA3.Text.Trim());
                }
                catch
                {
                    throw new Exception("所填写的A3不是数字");
                }
            }

            //检测A4数据有效性
            if (!string.IsNullOrEmpty(this.txtA4.Text.Trim()))
            {
                try
                {
                    decimal.Parse(this.txtA4.Text.Trim());
                }
                catch
                {
                    throw new Exception("所填写的A4不是数字");
                }
            }

            if (string.IsNullOrEmpty(this.txtWellCode.Text.Trim()))
            {
                throw new Exception("请输入井号");
            }

            if (!string.IsNullOrEmpty(this.txtWellDepth.Text.Trim()))
            {
                try
                {
                    decimal.Parse(this.txtWellDepth.Text.Trim());
                }
                catch
                {
                    throw new Exception("所填写的完钻深度不是数字");
                }
            }

            return true;
        }

        /// <summary>
        /// 绑定单井元数据
        /// </summary>
        /// <param name="singleRow"></param>
        private void BindSingleModel(SingleWellModel.SINGLEWELLRow singleRow)
        {
            if (!singleRow.IsA0Null())
            {
                this.txtA0.Text = singleRow.A0.ToString();
            }
            if (!singleRow.IsA3Null())
            {
                this.txtA3.Text = singleRow.A3.ToString();
            }
            if (!singleRow.IsA4Null())
            {
                this.txtA4.Text = singleRow.A4.ToString();
            }
            if (!singleRow.IsBEGINDATENull())
            {
                this.txtBEGINDATE.Text = singleRow.BEGINDATE.ToShortDateString();
            }
            if (!singleRow.IsBEGINWORKDATENull())
            {
                this.txtBeginWorkDate.Text = singleRow.BEGINWORKDATE.ToShortDateString();
            }
            if (!singleRow.IsFINISHDATENull())
            {
                this.txtFINISHDATE.Text = singleRow.FINISHDATE.ToShortDateString();
            }
            if (!singleRow.IsFINISHWORKDATENull())
            {
                this.txtFinishWorkDate.Text = singleRow.FINISHWORKDATE.ToShortDateString();
            }
            if (!singleRow.IsWELLDEPTHNull())
            {
                this.txtWellDepth.Text = singleRow.WELLDEPTH.ToString();
            }
            if (!singleRow.IsDATAFILENAMENull())
            {
                this.txtDatafileName.Text = singleRow.DATAFILENAME;
            }
            if (!singleRow.IsSTATUSIDNull())
            {
                this.hdfCurrentStatusID.Value = singleRow.STATUSID.ToString();//赋值当前状态
            }
            if (!singleRow.IsWELLTYPENull())
            {
                this.txtWellType.Text = singleRow.WELLTYPE;
            }
            if (!singleRow.IsWORKMODENull())
            {
                this.txtWorkMode.Text = singleRow.WORKMODE;
            }
            /*******************************
             * add by guoyin 2014-03-25
             * 增加单井类型和子类型(数据加载)
             *******************************/
            if (!singleRow.IsCATEGORYNull())
            {
                this.ddlType.SelectedValue = singleRow.CATEGORY;
            }
            //设置隐藏域
            if (!singleRow.IsCATEGORYDETAILNull())
            {
                //初始化详细类别
                if (this.ddlType.SelectedIndex > 0)
                {
                    DataSet dtDetail = CodeTableService.GetCodeTableDataByType(ddlType.SelectedValue);
                    if (dtDetail != null && dtDetail.Tables.Count > 0)
                    {
                        this.ddlDetailType.DataSource = dtDetail;
                        this.ddlDetailType.DataTextField = "Code_Desc";
                        this.ddlDetailType.DataValueField = "CodeTableID";
                        this.ddlDetailType.DataBind();
                        this.ddlDetailType.Items.Insert(0, new ListItem("--请选择--", "-1"));
                        this.ddlDetailType.SelectedValue = singleRow.CATEGORYDETAIL;
                    }
                }
            }

            /* end */
            this.txtWellCode.Text = singleRow.WELLCODE;
        }

        /// <summary>
        /// 绑定详细信息
        /// </summary>
        /// <param name="detailDt"></param>
        private void BindDetailModel(SingleWellModel.WELLDATADETAILDataTable detailDt)
        {
            if (detailDt != null)
            {
                this.gv_SingleWellDetail.DataSource = detailDt;
                this.gv_SingleWellDetail.DataBind();
            }
        }

        private void BindDetail()
        {
            DataTable detailDatatable = null;
            if (this.gv_SingleWellDetail.DataSource == null)
            {
                detailDatatable = new DataTable();
                detailDatatable.Columns.Add("DETAILID");
                detailDatatable.Columns.Add("WellDataID");
                detailDatatable.Columns.Add("detailname");
                detailDatatable.Columns.Add("A4");
                detailDatatable.Columns.Add("A3");
                detailDatatable.Columns.Add("A0");
                detailDatatable.Columns.Add("PageNum");
            }
            else
            {
                detailDatatable = this.gv_SingleWellDetail.DataSource as DataTable;
            }

            DataRow newDetail = detailDatatable.NewRow();
            newDetail["DETAILID"] = Guid.NewGuid().ToString();
            newDetail["WellDataID"] = this.m_WellDataID;
            newDetail["detailname"] = this.txtdetailname.Text.Trim();
            int a4 = -1;
            int a3 = -1;
            int a0 = -1;
            int pageNum = -1;

            if (!string.IsNullOrEmpty(this.txtDetailA4.Text.Trim()))
            {
                if (int.TryParse(this.txtDetailA4.Text.Trim(), out a4))
                {
                    newDetail["A4"] = a4;
                }
                else
                {
                    throw new Exception("输入的A4详细项不是整数");
                }
            }
            if (!string.IsNullOrEmpty(this.txtDetailA3.Text.Trim()))
            {
                if (int.TryParse(this.txtDetailA3.Text.Trim(), out a3))
                {
                    newDetail["A3"] = a3;
                }
                else
                {
                    throw new Exception("输入的A3详细项不是整数");
                }
            }
            if (!string.IsNullOrEmpty(this.txtDetailA0.Text.Trim()))
            {
                if (int.TryParse(this.txtDetailA0.Text.Trim(), out a0))
                {
                    newDetail["A0"] = a0;
                }
                else
                {
                    throw new Exception("输入的A0详细项不是整数");
                }
            }
            if (!string.IsNullOrEmpty(this.txtPageNum.Text.Trim()))
            {
                if (int.TryParse(this.txtPageNum.Text.Trim(), out pageNum))
                {
                    newDetail["PageNum"] = pageNum;
                }
                else
                {
                    throw new Exception("输入的定位页码详细项不是整数");
                }
            }
            detailDatatable.Rows.Add(newDetail);

            ///清空文本框
            this.txtdetailname.Text = string.Empty;
            this.txtDetailA4.Text = string.Empty;
            this.txtDetailA3.Text = string.Empty;
            this.txtDetailA0.Text = string.Empty;
            this.txtPageNum.Text = string.Empty;

            this.gv_SingleWellDetail.DataSource = detailDatatable;
            this.gv_SingleWellDetail.DataBind();
        }

        protected void gv_SingleWellDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                DataTable data = this.gv_SingleWellDetail.DataSource as DataTable;
                DataRow currentDr = data.Rows[e.RowIndex];

                if (currentDr["DetailID"] != null && currentDr["DetailID"] != DBNull.Value)
                {
                    this.m_ISingleWellService.DeleteDetail(currentDr["DetailID"].ToString());
                }

                data.Rows.RemoveAt(e.RowIndex);
                this.gv_SingleWellDetail.DataSource = data;
                this.gv_SingleWellDetail.DataBind();
            }
            catch
            {
                Alert("操作出现异常，请重新再试！");
            }
        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //初始化详细类别
            DataSet dtDetail = CodeTableService.GetCodeTableDataByType(ddlType.SelectedValue);
            if (dtDetail != null && dtDetail.Tables.Count > 0)
            {
                this.ddlDetailType.DataSource = dtDetail;
                this.ddlDetailType.DataTextField = "Code_Desc";
                this.ddlDetailType.DataValueField = "CodeTableID";
                this.ddlDetailType.DataBind();
                this.ddlDetailType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
        }
        #endregion

        #region 流程操作
        private void FlowStart(Guid recordID, Guid currentUserID, int currentStatusID)
        {
            WorkFlowModel oWorkFlowModel = new WorkFlowModel();
            WorkFlow oWorkFlow = new WorkFlow();
            oWorkFlowModel.CommentMessage = string.Empty;//获取评论，在上报时候，基本是没有评论的。
            oWorkFlowModel.TableID = (int)ArchiveTableEnum.SingleWell;//获取表ID
            oWorkFlowModel.FromUserID = currentUserID;//获取当前用户ID
            oWorkFlowModel.RecordID = recordID;
            if (currentStatusID > 0)
            {
                oWorkFlowModel.FromStatusID = currentStatusID;
            }
            else
            {
                oWorkFlowModel.FromStatusID = new WorkFlowManager().GetOriginalStastuIDByTableID(ArchiveTableEnum.SingleWell);
            }
            WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
            List<WorkFlowMessageStatusRule> listRule = ruleCache.GetRuleByStatusID(oWorkFlowModel.FromStatusID);
            WorkFlowMessageStatusRule rule = listRule[0];//取第一个驱动
            oWorkFlowModel.OperateID = rule.OperateID;//取驱动的ID
            oWorkFlow.FlowStart(oWorkFlowModel, true);//启动流程
        }

        private void FlowProcess(Guid recordID, Guid currentUserID, int currentStatusID)
        {
            WorkFlowModel oWorkFlowModel = new WorkFlowModel();
            WorkFlow oWorkFlow = new WorkFlow();
            oWorkFlowModel.OperateLogID = Guid.NewGuid();
            oWorkFlowModel.CommentMessage = string.Empty;//获取评论，在上报时候，基本是没有评论的。
            oWorkFlowModel.TableID = (int)ArchiveTableEnum.SingleWell;//获取表ID
            oWorkFlowModel.FromUserID = currentUserID;//获取当前用户ID
            oWorkFlowModel.RecordID = recordID;
            if (currentStatusID > 0)
            {
                oWorkFlowModel.FromStatusID = currentStatusID;
            }
            else
            {
                oWorkFlowModel.FromStatusID = new WorkFlowManager().GetOriginalStastuIDByTableID(ArchiveTableEnum.SingleWell);
            }
            WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
            WorkFlowMessageStatusRule nextRule = ruleCache.GetRuleByStatusIDAndOperateName(oWorkFlowModel.FromStatusID, "上报");
            oWorkFlowModel.OperateID = nextRule.OperateID;//取驱动的ID
            oWorkFlow.FlowProcess(oWorkFlowModel);//启动流程
        }
        #endregion

        public string btnSaveAndSendSingelWellText
        {
            get
            {
                if (this.IsFromDataManage)
                {
                    return "保存";
                }
                else
                {
                    return "保存并上报";
                }
            }
        }

        public bool IsFromDataManage
        {
            get
            {
                if (!string.IsNullOrEmpty(this.Request.QueryString["IsFromDataManage"]) && this.Request.QueryString["IsFromDataManage"].ToString().ToLower() == "true")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}